<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="default"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" sortable />
      <el-table-column label="渠道名称" align="center" prop="name" />
      <el-table-column label="渠道编码" align="center" prop="code" />
      <el-table-column label="是否收费" align="center" prop="charge">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.charge" active-color="#00E266" @change="handleChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="功能显示" align="center" prop="functionShow" />
      <el-table-column label="创建日期" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="渠道名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入渠道名称" />
        </el-form-item>
        <el-form-item label="渠道编码：" prop="code">
          <el-input v-model="form.code" placeholder="请输入渠道编码" />
        </el-form-item>
        <el-form-item label="是否收费" prop="charge">
          <el-switch v-model="form.charge" active-color="#00E266"></el-switch>
        </el-form-item>
        <el-form-item label="功能显示" prop="functionIds">
          <div style="display: flex;align-items: center;flex-wrap: wrap">
            <div v-for="(item, index) in functionData" :key="index" style="position: relative">
              <div style="display: flex;align-items: center;padding-bottom: 5px;">
                <div style="position: relative;">
                  <span>{{ item.name }}</span>
                  <el-popover
                    placement="right"
                    width="200"
                    trigger="hover">
                    <el-image :src="item.examplePic"></el-image>
                    <i class="el-icon-question" style="position: absolute;top: 0" slot="reference"></i>
                  </el-popover>
                </div>
                <el-switch v-model="item.checked" active-color="#00E266" style="margin: 0 20px 0 20px" @change="handleSwitchChange($event, item, index)"></el-switch>
              </div>
              <span style="color: #FFA500;font-size: 10px;position: absolute;bottom: -12px;left: 0;" v-if="item.delay && !item.checked">{{ item.delay }}分钟后显示</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="设置" :visible.sync="hideOpen" :close-on-click-modal="false" width="35%">
      <el-form ref="hideForm" :model="hideForm" :rules="hideRules" label-width="80px">
        <el-form-item label="安装app后" prop="delay">
          <el-input placeholder="请输入时间" type="number" v-model="hideForm.delay">
            <template slot="append">分钟后显示该功能</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHideForm">确定</el-button>
        <el-button @click="hideOpen = false">暂不设置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getChannelList, getFunctionList, saveChannelInfo, removeChannelInfo } from "@/api/shuiyin/shuiyin";

  export default {
    name: "Channel",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 租户管理表格数据
        tenantList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            { required: true, message: "渠道名称不能为空", trigger: "blur" }
          ],
          code: [
            { required: true, message: "渠道编码不能为空", trigger: "blur" }
          ],
          // functionIds: [
          //   { required: true, message: "请选择功能", trigger: "change" }
          // ],
        },
        // 功能数据
        functionData: [],
        // 临时存储功能数据的
        tempData: [],
        hideOpen: false,
        hideForm: {
          delay: 0
        },
        delayIndex: 0,
        hideRules: {
          delay: [
          { required: true, message: "时间不能为空", trigger: "blur" }
          ]
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询租户管理列表 */
      getList() {
        this.loading = true;
        getChannelList(this.queryParams).then(response => {
          this.tenantList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          code: null,
          charge: false,
          functionIds: null,
          // functionInfos: '[]'
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      async handleAdd() {
        this.reset();
        this.functionData = await this.getFunction();
        this.functionData.forEach(element => {
          element.checked = false;
        })
        this.open = true;
        this.title = "添加";
      },
      /** 修改按钮操作 */
      async handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        this.form = JSON.parse(JSON.stringify(row));
        this.functionData = await this.getFunction();

        const delayArray = row.functionInfos?.filter(v => v.delay);
        const delayIdArray = row.functionInfos?.filter(v => v.delay).map(ele => {return ele.functionId})
        const checkedArray = row.functionInfos?.filter(v => !v.delay).map(item => {return item.functionId});

        this.functionData.forEach(element => {
          element.checked = checkedArray?.includes(element.id);
          element.delay = delayIdArray?.includes(element.id) ? delayArray.filter(v=>v.functionId === element.id)[0].delay : null;
        })
        this.open = true;
        this.title = "修改";
      },
      handleSwitchChange(event, item, index) {
        const array = ['视频换脸', '图片换脸', '视频模板', '图片模板', '我的收藏', '提取视频立即制作按钮']
        if (array.includes(item.name) && !event) {
          this.hideForm.delay = item.delay;
          this.delayIndex = index;
          this.hideOpen = true;
        } else {
          item.delay = null;
        }
        this.$forceUpdate()
      },
      submitHideForm() {
        this.$refs.hideForm.validate((valid) => {
          if (valid) {
            this.functionData[this.delayIndex].delay = this.hideForm.delay;
            this.hideOpen = false;
          }
        })
      },
      // 功能数据
      getFunction() {
        return new Promise(resolve => {
          getFunctionList({pageNum: 1,pageSize: 1000}).then(response => {
            resolve(response.rows)
          })
        })
      },
      handleChange(row) {
        saveChannelInfo(row).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.tempData = [];
        this.functionData.forEach(element => {
          if (element.checked) {
            this.tempData.push(element.id)
          }
        })
        // this.form.functionIds = this.tempData.length > 0 ? this.tempData.join(',') : null;
        const array = this.functionData.filter(item => item.delay || item.checked).map(v=> {
          return {
            delay: v.delay ? +v.delay : null,
            functionId: v.id,
            functionName: v.name
          }
        });
        this.form.functionIds = JSON.stringify(array)
        console.log(array, '11')
        // return
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              saveChannelInfo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              saveChannelInfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const channelIds = row.id || this.ids;
        this.$modal.confirm('是否确认删除渠道管理编号为"' + channelIds + '"的数据项？').then(function() {
          return removeChannelInfo(channelIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    }
  };
</script>
